package com.quasar.hpatient.module.mine_phone;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mob.MobSDK;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_regist.RegistBean;

import java.util.HashMap;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.User;
import lib.quasar.widget.timer.TimerView;
import okhttp3.RequestBody;

/**
 * description: 修改手机号
 * created by kalu on 2018/5/17 13:37
 */
public class MinePhonePresenter implements BasePresenter {

    @SuppressLint("CheckResult")
    final void sendCode(MinePhoneView view, TimerView timer, TextView button, String number) {

        if (null == view || null == timer || null == button)
            return;

        if (TextUtils.isEmpty(number) || number.length() != 11) {
            view.toast("获取用户手机号发生错误");
            return;
        }

        final Pattern compile1 = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        if (!compile1.matcher(number).matches()) {
            view.toast("用户手机号格式错误");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.getVerificationCode(BaseConstant.MOB_PHONE, number);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {

                    view.toast(aBoolean ? "发送验证码成功" : "发送验证码失败");
                    if (aBoolean) {

                        view.setVisibility(button, aBoolean ? View.GONE : View.VISIBLE);
                        view.setVisibility(timer, aBoolean ? View.VISIBLE : View.GONE);

                        timer.setOnCountdownChangeListener(() -> {
                            view.setVisibility(button, aBoolean ? View.VISIBLE : View.GONE);
                            view.setVisibility(timer, aBoolean ? View.GONE : View.VISIBLE);
                        });
                        timer.startTimer();
                    }
                });
    }

    @SuppressLint("CheckResult")
    final void modifyPhone(MinePhoneView view, String codes, String password, String number) {

        if (TextUtils.isEmpty(number) || number.length() != 11) {
            view.toast("获取用户手机号发生错误");
            return;
        }

        final Pattern compile1 = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        if (!compile1.matcher(number).matches()) {
            view.toast("用户手机号格式错误");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            view.toast("密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(codes)) {
            view.toast("验证码不能为空");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.submitVerificationCode(BaseConstant.MOB_PHONE, number, codes);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    view.toast(aBoolean ? "验证码验证成功" : "验证码验证失败");
                    if (!aBoolean) return;

                    final HashMap<String, Object> map = new HashMap<>();
                    map.put(HttpParams.PASSWORD, password);
                    map.put(HttpParams.PHONE, number);
                    map.put(HttpParams.USER_TYPE, HttpParams.USER_TYPE);

                    final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_12);
                    final Observable observable = HttpClient.getSingleHolder().getHttpService().modifyPassword(params);

                    request(observable, new OnModelAcceptChangeListener<RegistBean>() {

                        @Override
                        public void modelSucc(RegistBean result) {
                            final User user = DBManager.getInstance().syncGetUserModel();
                            user.setPhone(number);
                            DBManager.getInstance().updataUserModel(user);
                            view.toast("修改手机号成功");
                        }

                        @Override
                        public void modelFail() {
                            view.toast("修改手机号失败");
                        }
                    });
                });
    }

    @Override
    public void recycler() {
    }
}
